package config

import (
	"fmt"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/clients/config_client"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/zeromicro/go-zero/core/jsonx"
	"github.com/zeromicro/go-zero/core/logx"
)

func NewClient(c *Config) (client config_client.IConfigClient) {
	//添加服务器地址+端口
	serverConfigs := []constant.ServerConfig{
		*constant.NewServerConfig(
			c.NaCosConf.Address,
			c.NaCosConf.Port,
			constant.WithScheme("http"),
			constant.WithContextPath("/nacos"),
		),
	}

	clientConfig := *constant.NewClientConfig(
		constant.WithNamespaceId(c.NaCosConf.Namespace),
		constant.WithTimeoutMs(5000),
		constant.WithNotLoadCacheAtStart(true),
		constant.WithLogDir("/tmp/nacos/log"),
		constant.WithCacheDir("/tmp/nacos/cache"),
		constant.WithUsername(c.NaCosConf.Username),
		constant.WithPassword(c.NaCosConf.Password),
		constant.WithLogLevel(c.NaCosConf.LogLevel),
	)

	// Another way of create naming client for service discovery (recommend)
	//namingClient, err := clients.NewNamingClient(
	//	vo.NacosClientParam{
	//		ClientConfig:  &clientConfig,
	//		ServerConfigs: serverConfigs,
	//	},
	//)

	// Another way of create config client for dynamic configuration (recommend)
	configClient, err := clients.NewConfigClient(
		vo.NacosClientParam{
			ClientConfig:  &clientConfig,
			ServerConfigs: serverConfigs,
		},
	)
	if err != nil {
		panic("创建动态客户端失败,error=" + err.Error())
	}
	return configClient
}

func WatchConfig(configClient config_client.IConfigClient, originDataId string, originGroup string, configObject interface{}) {

	content, err := configClient.GetConfig(vo.ConfigParam{
		DataId: originDataId,
		Group:  originGroup})
	if err != nil {
		panic("获取配置信息失败,error=" + err.Error())
	}

	err = jsonx.UnmarshalFromString(content, &configObject)
	if err != nil {
		logx.Errorf("dataId:%s group:%s json失败 %s error:%s", originDataId, originGroup, err.Error())
	}

	if err := configClient.ListenConfig(vo.ConfigParam{
		DataId: originDataId,
		Group:  originGroup,
		OnChange: func(namespace, group, dataId, data string) {
			fmt.Printf("dataId:%s,group:%s,result:%s", originDataId, originGroup, data)
			err := jsonx.UnmarshalFromString(data, &configObject)
			if err != nil {
				logx.Errorf("dataId:%s group:%s json失败 %s error:%s", originDataId, originGroup, err.Error())
			}
		},
	}); err != nil {
		logx.Errorf("监听配置 dataId:%s group:%s 异常 error:%s", originDataId, originGroup, err.Error())
	}
}
